package pl.un4giv3n.mightvsmagic.action.clan;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import pl.un4giv3n.mightvsmagic.action.PersistenceAction;
import pl.un4giv3n.mightvsmagic.entity.Clan;
import pl.un4giv3n.mightvsmagic.entity.Guardian;
import pl.un4giv3n.mightvsmagic.entity.User;

public class SearchClanAction extends PersistenceAction{

	private static final long serialVersionUID = 1L;
	private User user;
	private String clanName;
	private Clan clan;
	private List<Guardian> guardianList;

	@SuppressWarnings("unchecked")
	@Override
	public String execute() {
		EntityManager entityManager = getEntityManager();
		user = getSessionUser(entityManager);
		if (user == null) {
			addActionError("Zaloguj się");
			entityManager.close();
			return LOGIN;
		}
		Query query = entityManager.createNamedQuery("find.clan.by.name");
		query.setParameter("name", clanName);
		List<Clan> clans = query.getResultList();
		if(clans == null || clans.isEmpty()){
			Query gQuery = entityManager.createNamedQuery("find.all.guardians");
			guardianList = gQuery.getResultList();
			entityManager.close();
			addActionError("Nie znaleziono klanu");
			return INPUT;
		}
		clan = (Clan) query.getResultList().get(0);
		entityManager.close();
		return SUCCESS;
	}

	public List<Guardian> getGuardianList() {
		return guardianList;
	}

	public Clan getClan() {
		return clan;
	}
	
	public boolean isCanJoinClan(){
		return user.getClan() == null;
	}
	
	public boolean isCanLeaveClan(){
		return user.getClan() != null && user.getClan().getId() == clan.getId();
	}

	public String getClanName() {
		return clanName;
	}

	public void setClanName(String clanName) {
		this.clanName = clanName;
	}
	
}
